<!-- WechatLogin.vue -->
<template>
  <div class="wechat-login">
    <div v-if="!isLoggedIn">
      <h2>微信登录</h2>
      <div class="qrcode-container">
        <qrcode-vue :value="authUrl" :size="200" level="H" />
      </div>
      <p>请使用微信扫描二维码登录</p>
    </div>
    <div v-else>
      <h2>欢迎, {{ userInfo.nickname }}</h2>
      <img :src="userInfo.avatar" alt="头像" class="avatar" />
      <button @click="logout">退出登录</button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import axios from 'axios'
import QrcodeVue from 'qrcode.vue'

const isLoggedIn = ref(false)
const userInfo = ref({
  nickname: '',
  avatar: ''
})
const authUrl = ref('')

// 从本地存储获取token
const token = localStorage.getItem('access_token')
if (token) {
  isLoggedIn.value = true
  // 获取用户信息
  getUserInfo()
} else {
  // 生成微信授权URL
  generateAuthUrl()
}

function generateAuthUrl() {
  const appId = '你的微信应用APPID'
  const redirectUri = encodeURIComponent('http://your-domain.com/api/wechat/callback')
  const scope = 'snsapi_userinfo' // 需要用户信息时使用
  const state = 'STATE' // 可选参数，用于防止CSRF攻击

  authUrl.value = `https://open.weixin.qq.com/connect/qrconnect?appid=${appId}&redirect_uri=${redirectUri}&response_type=code&scope=${scope}&state=${state}#wechat_redirect`
}

async function getUserInfo() {
  try {
    const response = await axios.get('/api/user/me', {
      headers: {
        Authorization: `Bearer ${localStorage.getItem('access_token')}`
      }
    })
    userInfo.value = response.data
  } catch (error) {
    console.error('获取用户信息失败:', error)
    logout()
  }
}

function logout() {
  localStorage.removeItem('access_token')
  isLoggedIn.value = false
  userInfo.value = {
    nickname: '',
    avatar: ''
  }
  generateAuthUrl()
}

// 检查URL中是否有微信返回的code
onMounted(() => {
  const urlParams = new URLSearchParams(window.location.search)
  const code = urlParams.get('code')

  if (code) {
    // 发送code到后端
    exchangeCodeForToken(code)
  }
})

async function exchangeCodeForToken(code) {
  try {
    const response = await axios.post('/api/wechat/callback', {
      code: code
    })

    const { access_token, user_info } = response.data
    localStorage.setItem('access_token', access_token)
    isLoggedIn.value = true
    userInfo.value = user_info

    // 清除URL中的code参数
    window.history.replaceState({}, document.title, window.location.pathname)
  } catch (error) {
    console.error('登录失败:', error)
  }
}
</script>

<style scoped>
.wechat-login {
  text-align: center;
  padding: 20px;
}

.qrcode-container {
  margin: 20px auto;
  padding: 10px;
  border: 1px solid #eee;
  display: inline-block;
}

.avatar {
  width: 100px;
  height: 100px;
  border-radius: 50%;
  margin: 10px;
}
</style>
